<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel='stylesheet' href='<%- rootUrl %>/res/adapter.css' />
<link rel='stylesheet' href='<%- rootUrl %>/node_modules/ckeditor-full/contents.css' />
<link rel='stylesheet' href='<%- rootUrl %>/node_modules/font-awesome/css/font-awesome.min.css' />
<style>
.article-content {overflow:auto}
.article-content img {max-width:100%;}
.appends-list {border:1px solid gainsboro}
.appends-list > div { padding:9px 12px }
.appends-list > div:not(:first-child) {font-size:15px;text-indent:0.5em}
.appends-list a {color:#3e62a6}
.appends-list a:hover {color:#0000ee}
.comment-list > div {border-bottom:1px solid gainsboro}
.comment-list > div:first-child {border-bottom: 0}
.comment-list > div > div:first-child {color:darkgrey;font-size:11px;margin-bottom:-0.5em}
.comment-list > div > div:nth-child(3) {color:darkgrey; font-size:11px;text-align:right;margin-top:-0.5em}
.subcomment-list { display:block; margin-left: 12px; margin-top:6px; border:1px solid gainsboro}
.subcomment-list > div {border-bottom:1px solid gainsboro}
.subcomment-list > div:last-child {border-bottom: 0}
.subcomment-list > div > div:first-child {color:darkgrey;font-size:11px;margin-bottom:-0.5em}
.subcomment-list > div > div:nth-child(3) {color:darkgrey; font-size:11px;text-align:right;margin-top:-0.5em}
.remove-icon {color:darkgrey;text-decoration:none;float:right}
.feedback-start {color:darkgrey}
.fa-warning{display:none;color:gold}
</style>
<script src="<%- rootUrl %>/node_modules/jquery/dist/jquery.min.js"></script>
<script src="<%- rootUrl %>/node_modules/ckeditor-full/ckeditor.js"></script>
<script src="<%- rootUrl %>/res/adapter.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<title><%- title+' - '+blocks[blockRoot] %></title>
</head>
<body class="body-nomargin">
<alljs-widget><message-top><%- message %></message-top></alljs-widget>
<%- components['signhead'] ? include(components['signhead'], this) : '' %>
<%- components['feedback'] ? include(components['feedback'], this) : '' %>
<div class="width-limit ">
<div class="padding-leftright">
<h1><b><%- title %></b>
    <% if(edit){ %>&emsp;<i class="fa fa-pencil" onclick="location.href='./articledit.html?id=<%- _id %>'" style="color:grey"></i><% } else { %><span style="font-size:0.35em;color:grey;word-break: keep-all">已超过30小时可编辑时间</span><% } %>
</h1>
<div class="adapt-panel" style="margin-bottom: 10px">
    <div class="adapt-two-left" style="color:dimgrey;padding:0 0 12px 12px"><a href="<%- produceUrl %>"><%- author %></a>&emsp;<%- publish %></div>
    <div class="adapt-two-right" style="padding-left:12px"><select style="color:lightgrey;background-color:white;font-size:11px;width:18em;border:none;outline:none" onfocus="this.defaultIndex=this.selectedIndex" onchange="this.selectedIndex=this.defaultIndex" >
        <option selected style="display:none">编辑于 <%- modify[modify.length-1][1] %> 共 <%- modify.length %> 次</option>
        <% for(let i=0;i<modify.length;i++){ %><option><%- modify[i][0] %> <%- i===0?'发布于':'编辑于' %> <%- modify[i][1] %></option><% } %>
    </select></div>
</div>
<div class="adapt-panel">
    <div data-content-path="0" class="adapt-two-left padding-rightbottom" >
        <div class="article-content padding-leftright">
<%- content %>
            <br/>
        </div>
        <a id="comment-anchor"></a>
        <div  class="article-comment-list adapt-panel padding-arround childs-padding-leftright">
            <div style="flex-grow:1;color:teal">分享&emsp;<i class="fa fa-wechat" onclick="javascript:window.sharePage(this, 'weixin')"></i>&emsp;<i class="fa fa-weibo" onclick="javascript:window.sharePage(this, 'sina')"></i>&emsp;<i class="fa fa-qq" onclick="javascript:window.sharePage(this, 'qqzone')"></i></div>
            <div style="flex-grow:0"><a class="feedback-start" href="javascript:;">举报/反馈/建议</a><i class="feedback fa fa-warning" onclick="javascript:window.feedback(this)"></i></div>
            <div style="flex-grow:0">阅读(<%- accesses %>)&emsp;<a id="fond-article-fonds" href="javascript:;">点赞(<%- fonds %>)</a>&emsp;<a href="#comment-anchor"><b id="comment-article-replys">评论(<%- replys %>)&emsp;我来说两句&emsp;</b></a></div>
        </div>
        <div id="comment-div" style="padding-bottom:12px;display:none">
            <div class="adapt-panel" style="background-color: gainsboro;">
                <div class="padding-arround" style="width:241px;flex-grow:1"><b>评论&nbsp;-&nbsp;</b><span id="comment-ref"></span></div>
                <div class="padding-arround" style="flex-grow:0"><input id="comment-basepath" type="hidden" value="0" /><button id="comment-publish">发表&nbsp;<i class="fa fa-send"></i></button>&emsp;<i class="fa fa-angle-double-up fa-lg"></i></div>
            </div>
            <div id="ckeditor"></div>
        </div>
        <div class="comment-list childs-padding-arround">
        </div>
    </div>
    <div class="adapt-two-right">
        <%- include('com.userpanel.html', this) %>
        <div class="appends-list" style="margin-top:24px;height:10em">
            <div><b><i class="fa fa-th"></i>&nbsp;扩展栏目</b></div>
        </div>
    </div>
</div>
</div>
</div>
<script>
var article_id = window.getUrlParam('id');

window.getPathOfNode = function(node){
    let contentPath = '';
    let firstNode = null;
    node.parents().each(function(){
        let thisPath = $(this).attr('data-content-path');
        if (thisPath != null){
            contentPath = thisPath + '/' + contentPath;
            if (firstNode == null)
                firstNode = $(this);
        }
    });
    if (contentPath.length > 1)
        contentPath = contentPath.substr(0, contentPath.length - 1);
    return {contentPath, firstNode};
};
window.getNodeOfPath = function(path){
    let paths = path.split('/');
    if (path.length === 0)
        return null;

    let node = $('.article-content:first').parent();
    if (path.length === 1)
        return path[0] === '0' ? node : null;

    for (let idx = 1; idx < paths.length; idx++){
        node = node.children(idx === 1 ? '.comment-list' : '.subcomment-list').children('div[data-content-path='+paths[idx]+']');
    }
    return node;
};
window.getCommentReference = function(contentPath, firstNode){
    let brief = '<%- author %>: "<%- title %>"';
    if (contentPath !== '0')
        brief =  firstNode.children('div:first').children('a:eq(1)').text() + ': "' + firstNode.children('p').text() + '"';
    if (brief.length > 24)
        brief = brief.substr(0, 24) + '..."';
    return brief;
};

window.appendCommentFondClick = function(region){
    $(region).find('a').each(function(){
        let node = $(this);
        let nodetxt = node.text();
        let nodehref = node.attr('href');
        if (nodehref === "#comment-anchor" && nodetxt.match(/^评论/)){
            node.click(function(){
                let {contentPath, firstNode} = window.getPathOfNode($(this));
                if (firstNode != null && contentPath !== ''){
                    $('#comment-div').css('display', 'block');
                    $('#comment-basepath').val(contentPath);
                    $('#comment-ref').text(window.getCommentReference(contentPath, firstNode));
                }
            });
        } else if (nodehref === "javascript:;" && (nodetxt.match(/^点赞/) || (nodetxt.match(/^已赞/)))){
            node.click(function(){
                let {contentPath, firstNode} = window.getPathOfNode($(this));
                if (firstNode != null && contentPath !== ''){
                    window.postFondRequest($(this), contentPath);
                }
            });
        }
    });

    $(region).find('a.remove-icon').click(function(){
        let {contentPath, firstNode} = window.getPathOfNode($(this));
        if (firstNode != null && contentPath !== ''){
            window.postCommentRequest(contentPath, '{[REMOVE]}');
        }
    });
};

window.showComments = function(comments, fonds){
    comments = comments.sort((d1, d2) => {
        let n1a=d1.path.split('/');
        let n2a=d2.path.split('/');
        if (n1a.length===n2a.length) {
            for (let i=0; i<n1a.length; i++){
                let div=parseInt(n1a[i])-parseInt(n2a[i]);
                if (div!==0)
                    return div;
            }
        }
        return n1a.length - n2a.length;
    });
    let nodes = {'0' : $('.comment-list:first')};
    nodes['0'].empty();
    nodes['0'].append('<div><b>网友热评</b></div>');
    if (comments.length === 0)
        nodes['0'].append('<div><a href="#comment-anchor" style="color:darkgrey"><span style="display: none">评论</span>还没有网友评论，快来抢沙发吧~</a></div>');

    comments.forEach(function(comment){
        let pos = comment.path.lastIndexOf('/');
        if (pos < 1)
            return;

        let basepath = comment.path.substr(0, pos);
        let contentpath = comment.path.substr(pos + 1);
        let parent = nodes[basepath];

        if (parent == null)
            return;

        if (basepath !== '0' && !parent.hasClass('subcomment-list')){
            parent.append('<span class="subcomment-list childs-padding-arround"></span>');
            nodes[basepath] = parent = parent.children('span');
        }
        let fondstr = '';
        if (fonds.includes(comment.path)){
            fondstr = '<a href="javascript:;" style="color:red">已赞('+comment.fonds+')</a>';
        }else{
            let fondtxt = comment.fonds === 0 ? '点赞' : '点赞('+comment.fonds+')';
            fondstr = '<a href="javascript:;">'+fondtxt+'</a>';
        }
        let replytxt = comment.replys === 0 ? '评论' : '评论('+comment.replys+')';
        parent.append('<div data-content-path="'+contentpath+'">' +
            '<div><a class="remove-icon" href="javascript:;">&emsp;×&emsp;</a><a href="javascript:;">'+comment.produceUser.nickname+'</a>&nbsp;'+comment.produceTime+'</div>' +
            comment.brief +
            '<div>'+fondstr+'&emsp;<a href="#comment-anchor">'+replytxt+'</a>&emsp;<i class="feedback fa fa-warning" onclick="javascript:window.feedback(this)"></i></div>' +
            '</div>');
        nodes[comment.path] = parent.children('div:last');
    });
};

window.setFond = function(node, plus_OR_isfond){
    let isFond = plus_OR_isfond;

    let txt = node.text();
    if (typeof(plus_OR_isfond) === 'number'){
        isFond = plus_OR_isfond > 0;

        let count = 0;
        let pos1 = txt.lastIndexOf('(');
        let pos2 = txt.lastIndexOf(')');
        if (pos2 > pos1)
            count = parseInt(txt.substring(pos1+1, pos2));
        count += plus_OR_isfond;
        txt = (isFond?'已赞':'点赞')+((count===0)?'':'('+count+')');
    }else{
        if (isFond)
            txt = txt.replace(/点赞/, '已赞');
        else
            txt = txt.replace(/已赞/, '点赞');
    }
    node.css('color', isFond ? 'red' : '');
    node.text(txt);
};

window.postFondRequest = function(node, path){
    $.post( './fond', {article_id, path}, (data, textStatus, jqXHR) => {
        if (!data.success) {
            showMessage(data.msg);
            return;
        }
        window.setFond(node, data.result);
    });
};

window.postCommentRequest = function(path, brief, cb){
    let senddata = {article_id};
    if (path != null && brief != null){
        senddata.basepath = path;
        brief = brief.replace(/https?:\/\/[^\/]+\/node_modules\/ckeditor-full\/plugins\/smiley\/images/g ,'<%- rootUrl %>/smiley');
        senddata.brief = brief;
    }
    $.post( './comment', senddata, (data, textStatus, jqXHR) => {
        if (!data.success) {
            showMessage(data.msg);
            return;
        }
        if (data.article_replys >= 0)
            $('#comment-article-replys').html('评论('+data.article_replys+')&emsp;我来说两句&emsp;');

        window.setFond($('#fond-article-fonds'), data.fonds.includes('0'));

        window.showComments(data.comments, data.fonds);
        window.appendCommentFondClick('.comment-list:first');

        if (cb)
            cb();
    });
};

window.feedback = function(node){
    var {contentPath, firstNode} = window.getPathOfNode($(node));
    window.showFeedbackDialog(article_id, contentPath, getCommentReference(contentPath, firstNode));
};

$(function(){
    var editor = CKEDITOR.replace('ckeditor',{ toolbar : 'Simple' });

    $('#comment-publish').click(function(){
        let brief = editor.getData();
        brief = window.handleCKEditorData(brief);
        if (brief === ''){
            showMessage('您的评论没有内容');
            return;
        }
        editor.setData('');
        window.postCommentRequest($('#comment-basepath').val(), brief);
    });

    $('#comment-publish').next('.fa-angle-double-up').click(function(){
        $('#comment-div').css('display', 'none');
    });

    window.appendCommentFondClick('.article-comment-list:first');

    window.postCommentRequest(null, null, function(){
        let path = window.getUrlParam('path');
        if (path){
            let node = window.getNodeOfPath(path);
            if (node != null && node.length > 0){
                $("html,body").animate({scrollTop:node.offset().top - "90" + "px"}, 200);
                node.children('div:first').css('font-weight', 'bold').css('color', 'red');
            }
        }
    });

    // feedback
    $('.feedback-start').click(function(){
        $(this).css('display', 'none');
        $('head').append('<style>.feedback{display:inline-block}</style>');
    });
});
</script>
</body>
</html>